import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import axios from 'axios'

export class HttpConfigService {
  config: AxiosRequestConfig
  httpService: AxiosInstance
  requestIntercaptor?: number
  responseIntercaptor?: number

  constructor(config: AxiosRequestConfig) {
    this.config = config
    this.httpService = axios.create(this.config)
    this.setInterceptors()
  }

  // 设置请求头后需要重新创建axios对象
  setHeaders(headers: { [key: string]: string | number | undefined }) {
    this.config = {
      ...this.config,
      headers: {
        ...this.config.headers,
        ...headers
      }
    }

    this.httpService = axios.create(this.config)
    this.setInterceptors()
  }

  setInterceptors() {
    // add a request interceptor
    this.requestIntercaptor = this.httpService.interceptors.request.use(
      function (config) {
        return config
      },
      function (error) {
        return Promise.reject(error)
      }
    )

    this.responseIntercaptor = this.httpService.interceptors.response.use(
      (response) => {
        // show global error message
        if (response?.data?.success === false) {
        }

        return response
      },
      function (error) {
        // realtime log
        console.error('API-ERROR : HttpConfigService -> response -> reject', JSON.stringify(error))
        return Promise.reject(error)
      }
    )
  }

  enableInterceptor() {
    this.setInterceptors()
  }

  disableInterceptor() {
    this.httpService.interceptors.request.eject(this.requestIntercaptor as number)
    this.httpService.interceptors.response.eject(this.responseIntercaptor as number)
  }
}

export const httpConfigService = new HttpConfigService({
  baseURL: import.meta.env.VITE_DOMAIN + import.meta.env.VITE_BASE_URL
})
